package com.zz.nondatain.view.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.zz.nondatain.base.BaseFragment;
import com.zz.nondatain.databinding.FragmentSignInBinding;
import com.zz.nondatain.service.LocationService;
import com.zz.nondatain.view.activity.ActiveSignInActivity;
import com.zz.nondatain.view.activity.AttendanceCalendarActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class SignInFragment extends BaseFragment<FragmentSignInBinding> {

    private static final String TAG = "SignInFragment";
    
    // 签到时间范围
    private static final String START_TIME = "00:00:00";
    private static final String END_TIME = "23:30:00";
    
    private Timer timer;
    private BroadcastReceiver locationReceiver;
    private boolean isInCheckInTimeRange = false;

    public static SignInFragment newInstance() {
        return new SignInFragment();
    }

    @Override
    protected void initView() {
        // 设置用户信息
        binding.tvUserName.setText("测试张");
        
        // 设置当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.getDefault());
        binding.tvCurrentDate.setText(dateFormat.format(new Date()));
        
        // 设置考勤范围时间
        String attendanceTimeRange = "考勤范围" + START_TIME + "-" + END_TIME;
        
        // 更新签到按钮状态
        updateSignInButtonState();
        
        // 更新当前时间并启动定时器
        updateCurrentTime();
    }

    @Override
    protected void initData() {
        // 注册位置广播接收器
        locationReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.zz.nondatain.LOCATION_UPDATE".equals(intent.getAction())) {
                    String location = intent.getStringExtra("location");
                    if (location != null) {
                        binding.tvLocation.setText(location);
                    }
                }
            }
        };

        // 注册广播接收器
        IntentFilter filter = new IntentFilter("com.zz.nondatain.LOCATION_UPDATE");
        requireActivity().registerReceiver(locationReceiver, filter);
        
        // 启动定位服务
        startLocationService();
    }

    @Override
    protected void initObservers() {
        // 设置点击事件监听
        setupClickListeners();
    }

    @Override
    protected FragmentSignInBinding getViewBinding(LayoutInflater inflater, ViewGroup container) {
        return FragmentSignInBinding.inflate(inflater, container, false);
    }
    
    /**
     * 设置点击事件监听
     */
    private void setupClickListeners() {
        // 主动签到按钮点击事件
        binding.btnActiveSignIn.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), ActiveSignInActivity.class);
            startActivity(intent);
        });
        
        // 查看考勤规则点击事件
        binding.tvCheckRule.setOnClickListener(v -> {
            // 跳转到考勤规则页面
            showToast("跳转到考勤规则页面");
        });
        
        // 日期区域点击事件（跳转到考勤月历）
        binding.layoutDate.setOnClickListener(v -> {
            // 跳转到考勤月历页面
            Intent intent = new Intent(requireActivity(), AttendanceCalendarActivity.class);
            startActivity(intent);
        });
        
        // 签到按钮点击事件
        binding.btnSignIn.setOnClickListener(v -> {
            if (isInCheckInTimeRange) {
                // 签到逻辑
                performSignIn();
            } else {
                showToast("当前不在考勤时间范围内");
            }
        });
        
        // 重新定位按钮点击事件
        binding.btnRefreshLocation.setOnClickListener(v -> {
            showToast("正在重新定位...");
            startLocationService();
        });
    }
    
    /**
     * 执行签到操作
     */
    private void performSignIn() {
        // 这里应该添加实际的签到逻辑，例如调用API等
        showToast("签到成功！");
    }
    
    /**
     * 显示Toast消息
     */
    protected void showToast(String message) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 启动定位服务
     */
    private void startLocationService() {
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            requestPermissions(
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    1001);
        } else {
            // 启动定位服务
            Intent intent = new Intent(requireActivity(), LocationService.class);
            requireActivity().startService(intent);
        }
    }
    
    /**
     * 更新当前时间并启动定时器
     */
    private void updateCurrentTime() {
        if (timer != null) {
            timer.cancel();
        }
        
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(() -> {
                    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
                    String currentTime = timeFormat.format(new Date());
                    
                    // 更新签到按钮上的时间显示
                    binding.tvCurrentTime.setText(currentTime);
                    
                    // 检查是否在签到时间范围内
                    updateSignInButtonState();
                });
            }
        }, 0, 1000); // 每秒更新一次
    }
    
    /**
     * 更新签到按钮状态
     */
    private void updateSignInButtonState() {
        // 检查当前时间是否在签到范围内
        try {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
            
            // 获取当前时间
            Calendar now = Calendar.getInstance();
            int currentHour = now.get(Calendar.HOUR_OF_DAY);
            int currentMinute = now.get(Calendar.MINUTE);
            int currentSecond = now.get(Calendar.SECOND);
            String currentTimeStr = String.format(Locale.getDefault(), "%02d:%02d:%02d", 
                    currentHour, currentMinute, currentSecond);
            
            // 解析时间
            Date currentTime = format.parse(currentTimeStr);
            Date startTime = format.parse(START_TIME);
            Date endTime = format.parse(END_TIME);
            
            // 判断是否在范围内
            isInCheckInTimeRange = currentTime.after(startTime) && currentTime.before(endTime);
            
            // 更新按钮样式
            if (isInCheckInTimeRange) {
                // 在考勤时间范围内，按钮为蓝色可点击状态
                binding.btnSignIn.setBackgroundResource(com.zz.nondatain.R.drawable.circle_button_background);
                binding.btnSignIn.setClickable(true);
            } else {
                // 不在考勤时间范围内，按钮为浅蓝色不可点击状态
                binding.btnSignIn.setBackgroundResource(com.zz.nondatain.R.drawable.circle_button_inactive_background);
                binding.btnSignIn.setClickable(false);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        
        // 清理定时器
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        
        // 注销广播接收器
        if (locationReceiver != null) {
            requireActivity().unregisterReceiver(locationReceiver);
            locationReceiver = null;
        }
    }
} 